﻿using IcicleFramework.Components.Projectile;
using IcicleFramework.Entities;
using Microsoft.Xna.Framework;

namespace IcicleFramework.GameServices
{
    public delegate void ProjectileCreatedHandler(IGameObject projectile);

    public class ProjectileManager : GameService
    {
        public event ProjectileCreatedHandler OnProjectileCreated;

        private Pool<GameObject> projectilePool = new Pool<GameObject>(1000, t => t.Active)
        {
            Initialize = t =>
            {
                t.Active = true;
            },

            Deinitialize = t =>
            {
                t.Active = false;
            }
        };

        public override void Initialize() {}

        /// <summary>
        /// Creates a projectile with the provided specifications, given that such the creator IGameObject
        /// is allowed to spawn a projectile at this time and fires an event related to each projectile.
        /// </summary>
        /// <param name="projectileComponent">The ProjectileComponent containing the information on the Projectile to be fired.</param>
        /// <param name="position">The initial position of the projectile.</param>
        /// <param name="angle">The angle that the projectile will travel.</param>
        public IGameObject CreateProjectile(IProjectileComponent projectileComponent, Vector2 position, float angle)
        {
            IGameObject projectile = null;

            if (projectileComponent != null && projectileComponent.AbleToFire)
            {
                projectile = projectilePool.New();
                projectile.CloneAttributes(projectileComponent.Projectile);
                //projectile.Position = position;

                //Vector2 velocity = new Vector2((float) Math.Cos(angle) * projectile.MovementSpeed,
                //                                (float) Math.Sin(angle) * projectile.MovementSpeed);
                //projectile.Velocity = velocity;

                OnProjectileCreated(projectile);
            }

            return projectile;
        }
    }
}